package com.collage.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.collage.entity.Admin;
import com.collage.params.AdminParams;
import com.collage.service.AdminService;
import com.collage.util.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@Api(tags = "管理员接口集合")
@RestController
@RequestMapping("/admin")
public class AdminController {
	@Autowired
	private AdminService adminService;

	@GetMapping("/login")
	@ApiOperation("管理员登录接口")
	public Result adminLogin(Admin admin) {
		QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda()
				.eq(Admin::getUser, admin.getUser())
				.eq(Admin::getPassword, admin.getPassword());
		return Result.success(adminService.getOne(queryWrapper));
	}

	@GetMapping("/updatePassword")
	@ApiOperation("修改管理员密码接口")
	public Result updatePassword(Admin admin) {
		UpdateWrapper<Admin> updateWrapper = new UpdateWrapper<>();
		updateWrapper.lambda()
				.set(Admin::getPassword, admin.getPassword())
				.eq(Admin::getId, admin.getId());
		return adminService.update(updateWrapper) ? Result.success() : Result.failed("修改密码失败");
	}

	@GetMapping("/page")
	@ApiOperation("分页查询管理员")
	public Result pageList(AdminParams params) {
		QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
		if (!StringUtils.isEmpty(params.getName())) {
			queryWrapper.like("name", params.getName())
					.or().like("user", params.getName());
		}
		PageHelper.startPage(params.getPageNum(), params.getPageSize());
		PageInfo<Admin> pageInfo = new PageInfo<>(adminService.list(queryWrapper));
		return Result.success(pageInfo.getList(), pageInfo.getTotal());
	}

	@PostMapping("/edit")
	@ApiOperation("管理员新增或者修改接口")
	public Result edit(@RequestBody Admin admin) {
		QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(Admin::getUser, admin.getUser());
		Admin one = adminService.getOne(queryWrapper);
		if (StringUtils.isEmpty(admin.getId())) {
			if (one != null) {
				return Result.failed("该用户名已存在");
			}
			adminService.save(admin);
		} else {
			adminService.updateById(admin);
		}
		return Result.success();
	}

	@GetMapping("/delete/{id}")
	@ApiOperation("管理员删除接口")
	public Result deleteById(@PathVariable String id) {
		return adminService.removeById(id) ? Result.success() : Result.failed("删除失败");
	}
}